from flask import session, render_template, current_app, jsonify, request, g
# 导入蓝图对象
from info1 import constants, db
from info1.utils.commons import login_required
from . import new_blue
# 导入模型类User
from info1.models import User, News, Category, CommentLike, Comment
# 导入自定义的状态码
from info1.utils.response_code import RET


# 项目首页
@new_blue.route('/')
@login_required
def index():
    """
    展示用户信息
    1、尝试从redis中获取用户信息，
    2、如果有user_id,查询mysql获取用户的基本信息
    3、调用模型类中的to_dict方法
    4、返回数据给模板

    :return:
    """
    user = g.user

    try:
        news_list = News.query.filter().order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据异常')
    if not news_list:
        return jsonify(errno=RET.NODATA,errmsg='无新闻数据')
    news_dict_list= []
    for news in news_list:
        news_dict_list.append(news.to_dict())

    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    if not categories:
        return jsonify(errno=RET.NODATA,errmsg='无分类数据')
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    data = {
        'user_info':user.to_dict() if user else None,
        'news_dict_list':news_dict_list,
        'category_list':category_list
    }
    return render_template('news/index.html',data=data)

@new_blue.route('/news_list')
def get_news_list():
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')
    try:
        cid,page,per_page = int(cid),int(page),int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')
    filters = []
    if cid > 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.HOME_PAGE_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    news_list = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())
    data = {
        'news_dict_list':news_dict_list,
        'total_page':total_page,
        'current_page':current_page
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)

@new_blue.route('/<int:news_id>')
@login_required
def news_detail(news_id):
    user = g.user


    # 点击排行
    try:
        news_list = News.query.filter().order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据异常')
    if not news_list:
        return jsonify(errno=RET.NODATA,errmsg='无新闻数据')
    news_dict_list= []
    for index in news_list:
        news_dict_list.append(index.to_dict())
    # 新闻详情数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='无新闻数据')
    news.clicks += 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    data = {
        'user_info':user.to_dict() if user else None,
        'news_dict_list':news_dict_list,
        'news_detail':news.to_dict()
    }
    return render_template('news/detail.html',data=data)


@new_blue.route('/news_collect',methods=['POST'])
@login_required
def news_collection():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')
    if action not in ['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据错误')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='无新闻数据')
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    return jsonify(errno=RET.OK,errmsg='OK')














@new_blue.route('/news_comment',methods=['POST'])
@login_required
def comments_news():
    """
    评论新闻
    1、判断用户是否登录
    2、获取参数，news_id,comment,parent_id
    3、检查参数的完整
    4、校验news_id,parent_id转成整型
    5、根据news_id查询数据库
    6、实例化评论表对象，保存评论id、新闻id，新闻内容，
    7、提交数据返回结果

    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    news_id = request.json.get('news_id')
    parent_id = request.json.get('parent_id')
    content = request.json.get('comment')
    if not all([news_id,content]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失111')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误222')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='数据不存在')
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = content
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
    return jsonify(errno=RET.OK,errmsg='OK',data=comment.to_dict())


@new_blue.route('/comment_like',methods=['POST'])
@login_required
def comment_like():
    """
    点赞或取消点赞
    1、获取用户登录信息
    2、获取参数，comment_id,action
    3、检查参数的完整性
    4、判断action是否为add，remove
    5、把comment_id转成整型
    6、根据comment_id查询数据库
    7、判断查询结果
    8、判断行为是点赞还是取消点赞
    9、如果为点赞，查询改评论，点赞次数加1，否则减1
    10、提交数据
    11、返回结果

    :return:
    """
    user = g.user
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    if action not in ['add','remove']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='参数错误')
    try:
        comments = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    if not comments:
        return jsonify(errno=RET.NODATA,errmsg='评论不存在')
    if action == 'add':
        comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id,CommentLike.comment_id== comment_id).first()
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id
            db.session.add(comment_like_model)
            comments.like_count += 1
    else:
        comment_like_model = CommentLike.query.filter(CommentLike.user_id==user.id,CommentLike.comment_id==comment_id).first()
        if comment_like_model:
            db.session.delete(comment_like_model)
            comments.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')

    return jsonify(errno=RET.OK,errmsg='OK')


@new_blue.route('/followed_user',methods=['POST'])
@login_required
def followed_user():
    """
    关注与取消关注
    1、获取用户信息,如果未登录直接返回
    2、获取参数，user_id和action
    3、检查参数的完整性
    4、校验参数，action是否为followed，unfollow
    5、根据用户id获取被关注的用户
    6、判断获取结果
    7、根据对应的action执行操作，关注或取消关注
    8、返回结果
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    user_id = request.json.get('user_id')
    action = request.json.get('action')
    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    if action not in ['follow','unfollow']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    if not other:
        return jsonify(errno=RET.NODATA,errmsg='无用户数据')
    # 如果选择关注
    if action == 'follow':
        if other not in user.followed:
            user.followed.append(other)
        else:
            return jsonify(errno=RET.DATAEXIST,errmsg='当前用户已被关注')
    # 取消关注
    else:
        if other in user.followed:
            user.followed.remove(other)

    return jsonify(errno=RET.OK,errmsg='OK')



# 实现项目logo展示
@new_blue.route('/favicon.ico')
def favicon():
    # 使用应用上下文对象，调用flask源码中的发送静态文件给浏览器的方法，实现项目logo的展示
    return current_app.send_static_file('news/favicon.ico')
